from pymongo import MongoClient
import json
from bson import ObjectId

# 创建MongoDB客户端
client = MongoClient('mongodb://localhost:27017/medical_system')
db = client.medical_system

# 查询admin角色
role = db.roles.find_one({'name': 'admin'})
if not role:
    print("未找到admin角色")
    exit(1)

# 需要添加的权限
new_permissions = [
    'role:read',
    'role:create', 
    'role:update',
    'role:delete',
    'department:read',
    'department:create',
    'department:update',
    'department:delete'
]

# 获取当前权限
current_permissions = role.get('permissions', [])
print(f"当前权限数量: {len(current_permissions)}")

# 添加新权限
updated_permissions = list(set(current_permissions + new_permissions))
print(f"更新后权限数量: {len(updated_permissions)}")

# 更新到数据库
result = db.roles.update_one(
    {'_id': role['_id']},
    {'$set': {'permissions': updated_permissions}}
)

print(f"更新结果: 匹配 {result.matched_count}, 修改 {result.modified_count}")

# 再次查询验证
updated_role = db.roles.find_one({'_id': role['_id']})
print(f"更新后权限列表: {json.dumps(updated_role.get('permissions', []), indent=2, ensure_ascii=False)}")

# 关闭连接
client.close() 